package myProj2;

import java.util.ArrayList;

import myProj2.Project2;

public class Code {
	private Project2.Color[] slots = new Project2.Color[4];

	public Code(Project2.Color[] inColors) { // assumes being passed 4 colors
		this.slots = inColors;
	}

	/**
	 * default constructor is all empties
	 */
	public Code() {
		this.slots = new Project2.Color[] { Project2.Color.EMPTY, Project2.Color.EMPTY, Project2.Color.EMPTY,
				Project2.Color.EMPTY };
	}

	public Project2.Color[] getSlots() {
		return this.slots;
	}

	public boolean equals(Code other) {
		int pos = -1;
		boolean match = true;
		while (pos < 3 && (match = (this.slots[++pos] == other.slots[pos])))
			; // short circuiting
		return match;
	}

	public String toString() {
		String ans = "[ ";
		for (int i = 0; i < 4; i++) {
			ans += this.slots[i] + " ";
		}
		return ans + "]";
	}

	/**
	 * 
	 * @param inSoln
	 *            the solution code
	 * @return %10 gives white (wrong spot), /10 gives black (exact match)
	 */
	public int pegs(Code inSoln) {
		int ans = 0;
		for (int i = 0; i < 4; i++) {// index of this.code
			if (this.slots[i] == inSoln.slots[i]) { // first check if black, if
													// so, go to next slot
				ans += 10;
				continue;
			}
			for (int j = 0; j < 4; j++) { // index of soln.code
				if (i != j && this.slots[i] == inSoln.slots[j]) {
					ans++;
					break; // once granted a white peg, don't look for more with
							// same slot
				}
			}
		}
		return ans;
	}

	/**
	 * this method not only chooses a move (consistent with all responses) but
	 * it also shrinks the given list of moves to now match the peg result with
	 * the current guess
	 * 
	 * @param consistent
	 *            the current list of codes consistent with all responses so far
	 * @param inPegs
	 *            the pegs that the current guess received, represented as a
	 *            single int
	 * @return the next code it will guess, chosen equally among all consistent
	 *         codes (no AI)
	 */
	public Code pickMove(ArrayList<Code> consistent, int inPegs) {
		if (consistent == null || consistent.size() == 0)
			return null; // this should never happen
		int index = 0;
		while (index < consistent.size()) {
			if (this.pegs(consistent.get(index)) == inPegs) { // leave it in
																// list if
																// consistent
				index++; // move on to checking the next
			} else { // note that we don't increment index here, since next
						// entry will take its place
				consistent.remove(index); // remove from list if inconsistent
											// with latest peg entry
			}
		}
		if (consistent.size() == 0)
			return null; // this would mean human codemaker lied/mistaken
		return consistent.get(Project2.rangen.nextInt(consistent.size()));
	}
}
